import {
  Col,
  DatePicker,
  Form,
  Input,
  Radio,
  Row,
  Select,
  Upload,
  message,
  Button,
  TreeSelect,
  Spin,
} from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { history } from 'umi';
import React, { useState, useEffect } from 'react';
import {
  ucEmployeeSave,
  ucEmployeeGetId,
  ucEmployeeUpdate,
  fileAttachmentDownloadForAxios,
} from '@/services/deptControl';

import styles from './index.less';
import moment from 'moment';
import {
  getPolitical,
  getJob,
  getPosition,
  getStatus,
  getDepartmentTreeByRole,
  telephone,
  email,
  getOrgType,
} from '@/pages/features/dept/help';

const { Option } = Select;
const { TreeNode } = TreeSelect;

export enum StatusEnum {
  'EDIT' = 'EDIT',
  'ADD' = 'ADD',
  'DETAIL' = 'DETAIL',
}

export default (props: any) => {
  const {
    location: { state },
  } = props;
  const { type = StatusEnum.EDIT } = state;
  //是否为详情页面  详情页面所有不可操作 编辑
  const isDetail = type === StatusEnum.DETAIL;
  //机构是否可编辑
  const isOrgEdit = type === StatusEnum.ADD;

  const [form] = Form.useForm();

  const [isLoading, setIsLoading] = useState(false);

  // 编辑机构获取全部数据
  const [staff, setStaff] = useState({});

  // 部门树
  const [departmentTree, setdepartmentTree] = useState([]);

  // 加载
  const [loading, setLoading] = useState<boolean>(false);

  // 图片地址
  const [imageUrl, setImageUrl] = useState<any>(null);

  // 政治面貌
  const [political, setPolitical] = useState<any[]>([]);

  // 职务
  const [job, setJob] = useState<any[]>([]);

  // 岗位
  const [position, setPosition] = useState<any[]>([]);

  // 状态
  const [status, setStatus] = useState<any[]>([]);

  useEffect(async () => {
    setIsLoading(true);
    // 获取部门树
    const political: any = await getPolitical();
    setPolitical(political);

    const department: any = await getDepartmentTreeByRole({
      orgType: getOrgType(),
    });
    setdepartmentTree(department);

    const job: any = await getJob();
    setJob(job);

    const position: any = await getPosition();
    setPosition(position);

    const status: any = await getStatus();
    setStatus(status);

    await getDetail();
    setIsLoading(false);
  }, []);

  //获取详情数据
  const getDetail = async () => {
    // 根据id写入数据
    if (state?.id) {
      const result = await ucEmployeeGetId(state?.id);
      if (result?.code === 200) {
        // const tempResult = filterEmptyValueForObj(result?.data);
        const { data = {} } = result;
        form.setFieldsValue({
          ...result?.data,
          status: data.status ? String(data.status) : '',
          birthday: data?.birthday ? moment(data?.birthday) : '',
        });
        setStaff(data);
        const id = data?.photoRul;
        if (id) {
          //注意 这里获取图片 需要使用axios umi-request的有问题 请求二进制blob的会返回空值
          const res = await fileAttachmentDownloadForAxios({ id });
          if (res.data) {
            const blob = new Blob([res.data]);
            const reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function (e) {
              setImageUrl(e.target.result);
            };
          }
        }
      }
    }
  };

  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    getBase64(info.file.originFileObj, (imageUrl) => {
      setImageUrl(imageUrl);
      setLoading(false);
    });
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  function getBase64(
    img: Blob,
    callback: (arg0: string | ArrayBuffer | null) => any,
  ) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  function beforeUpload(file: { type: string; size: number }) {
    console.log('file', file);
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    // return false;
    return isJpgOrPng && isLt2M;
  }

  //
  // function customRequest(files: any) {
  //   console.log(files);
  //   const { file } = files;
  //   setImageFile(files.file);
  //   const reader = new FileReader();
  //   reader.readAsDataURL(file);
  //   reader.onload = function () {
  //     setImageUrl(this.result);
  //   };
  //
  //   // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  //   // if (!isJpgOrPng) {
  //   //     message.error('You can only upload JPG/PNG file!');
  //   // }
  //   // const isLt2M = file.size / 1024 / 1024 < 2;
  //   // if (!isLt2M) {
  //   //     message.error('Image must smaller than 2MB!');
  //   // }
  //   return true;
  // }

  const save = () => {
    form
      .validateFields()
      .then(async (value) => {
        value.file = value?.file?.file?.originFileObj;
        value.birthday = value.birthday
          ? moment(value.birthday).format('YYYY-MM-DD')
          : '';
        const formData = new FormData();
        state?.id && (value = { ...staff, ...value });
        delete value.deleted;
        delete value.createdTime;
        delete value.updatedTime;

        for (const i in value) {
          value[i] && formData.append(i, value[i]);
        }
        let res;
        if (state?.id) {
          res = await ucEmployeeUpdate(formData);
        } else {
          res = await ucEmployeeSave(formData);
        }
        if (res?.code === 200) {
          form.resetFields();
          history.push('/features/dept/staff');
        }
      })
      .catch((errorInfo) => {
        console.log(errorInfo);
      });
  };

  const tProps = {
    treeData: departmentTree,
    placeholder: '请选择机构',
    style: {
      width: '100%',
    },
  };

  const renderTreeNodes = (data: any) =>
    data.map((item: any) => {
      console.log('item', item);
      if (item.children) {
        item.disabled = !item.parentId;
        return (
          <TreeNode
            key={item.key}
            title={item.label}
            value={item.value}
            disabled={item.disabled}
          >
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          {...item}
          key={item.key}
          title={item.label}
          value={item.value}
        />
      );
    });

  return (
    <>
      <Spin spinning={isLoading}>
        <div className={styles.containerStyles}>
          <p>基本信息</p>
          <Form layout="vertical" form={form}>
            <Row>
              <Form.Item name="file">
                <Upload
                  disabled={isDetail}
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  // action={`/uaa/uc/user_center/change_avatar/${state.id}`}
                  beforeUpload={beforeUpload}
                  onChange={handleChange}
                  // customRequest={customRequest}
                >
                  {imageUrl ? (
                    <img
                      src={imageUrl}
                      alt="avatar"
                      style={{ width: '100%' }}
                    />
                  ) : (
                    uploadButton
                  )}
                  {/*<Button disabled={isDetail} icon={<UploadOutlined />}>*/}
                  {/*  更换头像*/}
                  {/*</Button>*/}
                </Upload>
                <div>人员编码: {staff?.employeeCode}</div>
              </Form.Item>
            </Row>
            <Row gutter={16}>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item
                  label="姓名"
                  name="name"
                  rules={[{ required: true, message: '请输入姓名!' }]}
                >
                  <Input disabled={isDetail} />
                </Form.Item>
              </Col>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item
                  label="性别"
                  name="gender"
                  rules={[{ required: true, message: '请选择你的性别!' }]}
                >
                  <Radio.Group disabled={isDetail}>
                    <Radio value={1}>男性</Radio>
                    <Radio value={2}>女性</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item label="工号" name="jobNumber">
                  <Input disabled={isDetail} />
                </Form.Item>
              </Col>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item label="出生日期" name="birthday">
                  <DatePicker disabled={isDetail} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item label="政治面貌" name="politicalStatus">
                  <Select
                    disabled={isDetail}
                    showSearch
                    placeholder="请选择政治面貌"
                    optionFilterProp="children"
                  >
                    {political.map((item) => (
                      <Option value={item?.dictValue} key={item?.dictValue}>
                        {item?.dictLabel}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item label="院校" name="graduateFrom">
                  <Input disabled={isDetail} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item
                  label="所属机构"
                  name="belongToOrg"
                  rules={[{ required: true, message: '请选择所属机构!' }]}
                >
                  <TreeSelect disabled={!isOrgEdit} {...tProps}>
                    {renderTreeNodes(tProps.treeData)}
                  </TreeSelect>
                </Form.Item>
              </Col>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item label="岗位" name="jobPosition">
                  <Select
                    disabled={isDetail}
                    showSearch
                    placeholder="请选择岗位"
                    optionFilterProp="children"
                  >
                    {position.map((item) => (
                      <Option value={item?.dictValue} key={item?.dictValue}>
                        {item?.dictLabel}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item
                  label="状态"
                  name="status"
                  rules={[{ required: true, message: '请选择状态!' }]}
                >
                  <Select
                    disabled={isDetail}
                    showSearch
                    placeholder="请选择状态"
                    optionFilterProp="children"
                  >
                    {status.map((item) => (
                      <Option value={item?.dictValue} key={item?.dictValue}>
                        {item?.dictLabel}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item label="职务" name="jobTitle">
                  <Select
                    disabled={isDetail}
                    showSearch
                    placeholder="请选择职务"
                    optionFilterProp="children"
                  >
                    {job.map((item) => (
                      <Option value={item?.dictValue} key={item?.dictValue}>
                        {item?.dictLabel}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item
                  label="手机"
                  name="phone"
                  rules={[
                    () => ({
                      validator(_, value) {
                        const msg = telephone(value);
                        if (!msg) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error(msg));
                      },
                    }),
                  ]}
                >
                  <Input disabled={isDetail} />
                </Form.Item>
              </Col>
              <Col span={12} className={styles.gutterRow}>
                <Form.Item
                  label="邮箱"
                  name="emailAddress"
                  rules={[
                    () => ({
                      validator(_, value) {
                        const msg = email(value);
                        if (!msg) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error(msg));
                      },
                    }),
                  ]}
                >
                  <Input disabled={isDetail} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        {!isDetail ? (
          <div className={styles.operatingContainer}>
            <Button
              onClick={() => {
                form.resetFields();
                history.push('/features/dept/staff');
              }}
            >
              取消
            </Button>
            <Button type="primary" onClick={save}>
              保存
            </Button>
          </div>
        ) : (
          <div className={styles.operatingContainer}>
            <Button
              onClick={() => {
                form.resetFields();
                history.push('/features/dept/staff');
              }}
            >
              返回
            </Button>
          </div>
        )}
      </Spin>
    </>
  );
};
